<template>
	<view class="page">
		<!-- <picker :range="pickerArray" @change="onPickerChange" :value="selectedIndex" range-key='name'
			:disabled='disabled'> -->
		<view class="list" @click="handleHouse">
			<text class="title required">房源名称</text>
			<input type="text" placeholder="请选择" v-model="form.name" disabled />
			<image src="https://hosue-omo.oss-cn-shenzhen.aliyuncs.com/assets/rightIcon.png" mode="" class="more_icon">
			</image>
		</view>
		<!-- </picker> -->
		<picker mode="date" @change="changeStarDate" :disabled="form.type != 'add'">
			<view class="list">
				<text class="title required">合同开始时间</text>
				<input type="text" placeholder="请选择" v-model="form.starDate" disabled />
				<image src="https://hosue-omo.oss-cn-shenzhen.aliyuncs.com/assets/rightIcon.png" mode=""
					class="more_icon" v-if="form.type == 'add'"></image>
			</view>
		</picker>
		<picker mode="date" @change="changeEndDate" :disabled="form.type != 'add'">
			<view class="list">
				<text class="title required">合同结束时间</text>
				<input type="text" placeholder="请选择" v-model="form.endDate" disabled />
				<image src="https://hosue-omo.oss-cn-shenzhen.aliyuncs.com/assets/rightIcon.png" mode=""
					class="more_icon" v-if="form.type == 'add'"></image>
			</view>
		</picker>
		<view class="list">
			<text class="title required">房屋租金</text>
			<input type="digit" placeholder="输入，整数数值" @input="filterInteger1" v-model="form.amount" disabled />
			<view class="jiage dis">
				元
			</view>
			<!-- <image src="https://hosue-omo.oss-cn-shenzhen.aliyuncs.com/assets/rightIcon.png" mode="" class="more_icon"></image> -->
		</view>
		<view class="list">
			<text class="title required">物业费</text>
			<input type="digit" placeholder="输入物业费（整数数值）" @input="filterInteger" v-model="form.manageAmount" disabled />
			<view class="jiage dis">
				元
			</view>
		</view>
		<view class="list">
			<text class="title required">水表数</text>
			<input type="digit" placeholder="输入水表数（最多两位小数）" @blur="handleBlur('waterMeterNum', $event)" 
			v-model="form.waterMeterNum" :disabled="form.type == 'preview'" />
			<view class="jiage dis">
				方
			</view>
		</view>
		<view class="list">
			<text class="title required">电表数</text>
			<input type="digit" placeholder="输入电表数（最多两位小数）" @blur="handleBlur('electricMeterNum', $event)"
				v-model="form.electricMeterNum" :disabled="form.type == 'preview'" />
			<view class="jiage dis">
				度
			</view>
		</view>
		<view class="list" style="margin-top: 16rpx;">
			<text class="biaoti required">上传合同文件 <text style="font-size: 24rpx;color:#333">（最多10张）</text></text>
			<!--  -->
		</view>
		<view class="list" style="padding-top: 0;">
			<view class="upload_box">
				<view style="position: relative;" v-for="(item,index) in form.attachments" :key="index">
					<image :src="item" mode="aspectFit" class="photo" @click="previewImage(index)"></image>
					<deleteBtn :index="index" @clearItem="deleteImage" v-if="form.type == 'add'"></deleteBtn>
				</view>
				<view class="upload" @click="handleUpload" v-if="form.type == 'add' &&form.attachments.length<10">
					<image src="/pagesA/static/xiangji.svg" mode="" class="upload_icon"></image>
					<text class="upload_text">上传图片</text>
				</view>
			</view>
		</view>
		<view style="height: 160rpx;" />


		<view class="bottom_box" v-if="form.type == 'add'">
			<view class="add_btn" @click="handleClick">
				提交
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		simpleDetail,
		houseAdd,
		contract
	} from './js/api.js'
	import config from '@/uitls/config.js';
	import http from '../../uitls/http.js';
	import {
		chooseImageFun
	} from '../../uitls/upload.js'
	const form = reactive({
		name: '',
		houseId: '',
		endDate: '',
		starDate: '',
		amount: '',
		deposit: '',
		attachments: [],
		manageAmount: '',
		appointmentId: '',
		type: '',

		waterMeterNum: '', //水表数
		electricMeterNum: '', //电表数
		typeId: null, //为2时是续约列表进来的
	})
	const filterInteger = (e) => {
		const value = e.target.value;
		form.deposit = value.replace(/[^\d]/g, '');
	}
	const filterInteger1 = (e) => {
		const value = e.target.value;
		form.amount = value.replace(/[^\d]/g, '');
	}
	const handleDecimalInput = (field, e) => {
		// let value = e.detail.value
		// // 清除非数字和非小数点字符
		// value = value.replace(/[^\d.]/g, '')
		// // 限制只能有一个小数点
		// value = value.replace(/\.{2,}/g, '.')
		// // 处理开头为小数点的情况
		// value = value.replace(/^\./g, '0.')
		// // 限制小数点后最多两位
		// value = value.replace(/(\.\d{2})\d*/g, '$1')
		// form[field] = value

		// e.detail.value = value; // 兼容小程序的元素引用
		// console.log(value,form[field],form)
	}
	const handleBlur = (field, e) => {
		// 从微信小程序事件中获取输入值
		  let value = e.detail.value || '';
		  
		  // 步骤1：清除所有非数字和非小数点的字符
		  value = value.replace(/[^\d.]/g, '');
		  
		  // 步骤2：处理多个小数点的核心逻辑
		  if (value.includes('.')) {
		    // 只保留第一个小数点，后面的小数点全部移除
		    const firstDotIndex = value.indexOf('.');
		    // 截取第一个小数点前的部分 + 第一个小数点 + 后面部分移除所有小数点
		    value = value.slice(0, firstDotIndex + 1) + 
		            value.slice(firstDotIndex + 1).replace(/\./g, '');
		  }
		  
		  // 步骤3：处理开头为小数点的情况（自动补0）
		  if (value.startsWith('.')) {
		    value = '0' + value;
		  }
		  
		  // 步骤4：限制小数点后最多两位
		  if (value.includes('.')) {
		    const parts = value.split('.');
		    // 整数部分 + 小数点 + 小数部分前两位
		    value = parts[0] + '.' + (parts[1] || '').slice(0, 2);
		  }
		  
		  // 步骤5：处理空值或纯0的特殊情况
		  // if (value === '0' || value === '0.') {
		  //   value = ''; // 可根据需求调整，如保留"0"则改为 value = value
		  // }
		  
		  // 更新数据并同步到视图（微信小程序推荐用:value绑定）
		  form[field] = value;
	}
	const pickerArray = ref([])
	const onPickerChange = (e) => {
		console.log(e)
	}
	const changeStarDate = (e) => {
		// console.log(e.target.value)
		form.starDate = e.target.value
	}
	const changeEndDate = (e) => {
		// console.log(e.target.value)
		form.endDate = e.target.value
	}


	const handleHouse = () => {
		// if(disabled.value){
		uni.navigateTo({
			url: '/pagesA/details/details?id=' + form.houseId
		})
		// }
	}
	// 预览图片
	const previewImage = (index) => {
		uni.previewImage({
			current: form.attachments[index], // 当前显示图片的URL
			urls: form.attachments.map(item => item), // 需要预览的图片URL列表
			success: () => {
				console.log('预览成功');
			},
			fail: (err) => {
				console.error('预览失败', err);
			}
		});
	};
	const getContract = async (id) => {
		let res = await contract(id)
		console.log('res====', res)
		if (res.data.code == 0) {
			let data = res.data.data
			form.name = data.houseName
			form.houseId = data.houseId
			form.endDate = data.endDate
			form.starDate = data.startDate
			form.amount = data.amount
			form.deposit = data.deposit
			form.attachments = data.attachments
			form.manageAmount = data.manageAmount || 0
			form.waterMeterNum = data.waterMeterNum 
			form.electricMeterNum = data.electricMeterNum 
		}
	}

	onLoad((options) => {
		console.log('options===', options)
		if (options.type == 'add') {
			form.appointmentId = options.id
			form.name = options.houseName
			form.houseId = options.houseId
			form.type = 'add'
			form.amount = options.price
			form.typeId = options.typeId //为2时是续约列表进来的
			form.manageAmount = options.manageAmount
		}

		if (options.type == 'preview') {
			form.type = 'preview'
			// form.houseId = 
			getContract(options.id)
		}

	})
	const handleClick = async () => {
		console.log('form==', form)
		let params = {
			"amount": form.amount,
			"appointmentId": form.appointmentId,
			"attachments": form.attachments,
			"endDate": form.endDate,
			"startDate": form.starDate,
			manageAmount: form.manageAmount,
			electricMeterNum:form.electricMeterNum,
			waterMeterNum:form.waterMeterNum
		}
		if (form.typeId == 2) params.typeId = 2
		console.log('params=====', params)
		let res = await houseAdd(params)
		if (res.data.code == 0) {
			http.isMssage('提交成功')
			uni.navigateBack()
		} else {
			http.isMssage(res.data.message)
		}
		console.log('这是返回===', res)
	}
	const handleUpload = async () => {
		let res = await chooseImageFun('contract')
		if (res.imageUrl) {
			form.attachments.push(res.imageUrl)
		}
	}
	const deleteImage = (index) => {
		form.attachments.splice(index, 1)
	}
</script>
<style>
	page {
		background: #F6F6F6 !important;
	}
</style>
<style lang="less" scoped>
	.list {
		display: flex;
		align-items: center;
		// justify-content: space-between;
		padding: 30rpx;
		background: #FFFFFF;
		position: relative;

		.title {
			font-family: PingFangSC-Regular;
			font-size: 28rpx;
			color: #333333;
			font-weight: 400;
			width: 190rpx;
			text-align: left;
		}

		input {
			font-size: 28rpx;
			width: 400rpx;
		}

		.jiage {
			min-width: 50rpx;
			height: 100%;
			// border: 1px solid red;
			position: absolute;
			// right: 30rpx;
			right: 16rpx;
			font-family: PingFangSC-Regular;
			font-size: 28rpx;
			color: #333333;
			text-align: right;
			font-weight: 400;
			padding: 0 10rpx;
		}

		.more_icon {
			position: absolute;
			right: 30rpx;
			top: 34rpx;
			width: 18rpx;
			height: 36rpx;
		}

		.biaoti {
			font-family: PingFangSC-Semibold;
			font-size: 32rpx;
			color: #000000;
			line-height: 36rpx;
			font-weight: 600;
			margin-right: 16rpx;
		}

		.state_text {
			font-family: PingFangSC-Regular;
			font-size: 28rpx;
			color: #CCCCCC;
			font-weight: 400;
			margin-left: 32rpx;
		}

		.textarea {
			width: 658rpx;
			height: 200rpx;
			// margin: auto;
			background: #F8F8F8;
			border: 1rpx solid rgba(238, 238, 238, 1);
			border-radius: 8rpx;
			padding: 16rpx;
			font-size: 28rpx;
		}

		.upload_box {
			width: 100%;
			// border: 1rpx solid rgba(238, 238, 238, 1);
			border-radius: 8rpx;
			// height: 200rpx;
			// display: flex;
			// flex-direction: column;
			// justify-content: center;
			// align-items: center;
			display: grid;
			grid-template-columns: 1fr 1fr 1fr 1fr;
			gap: 16rpx;

			.photo {
				height: 156rpx;
				width: 156rpx;
				// margin-right: 22.56rpx;
				border: 1rpx solid rgba(238, 238, 238, 1);
				border-radius: 8rpx;
			}

			.upload {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				border: 1rpx solid rgba(238, 238, 238, 1);
				border-radius: 8rpx;
				height: 156rpx;
				width: 156rpx;

				.upload_icon {
					width: 60rpx;
					height: 60rpx;
				}

				.upload_text {
					margin-top: 16rpx;
					font-family: PingFangSC-Regular;
					font-size: 28rpx;
					color: #999999;
					text-align: center;
					font-weight: 400;
				}
			}

		}
	}

	.bottom_box {
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx 0 60rpx 0;
		// background: #FFFFFF;
		width: 100%;
		background: #F6F6F6;

		.add_btn {
			width: 626rpx;
			height: 90rpx;
			line-height: 90rpx;
			background-image: linear-gradient(270deg, #F1B13F 0%, #F8D648 100%);
			border-radius: 50rpx;
			font-family: PingFangSC-Regular;
			font-size: 32rpx;
			color: #FFFFFF;
			text-align: center;
			font-weight: 400;
		}
	}
</style>